package com.zx._06_JVM.chapter_04_metrics.tool;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

/**
 * Java 自带工具，返回的数据都是两行，一行标题，一行数据
 */
public class JavaTool {

    public static Map<String, String> parseGcStat(List<String> lines) {
        Map<String, String> resMap = new HashMap<>();

        List<String> title = parseGcStatLine(lines.get(0));

        List<String> context = parseGcStatLine(lines.get(1));

        for (int i = 0; i < title.size(); i++) {
            resMap.put(title.get(i), context.get(i));
        }

        return resMap;
    }

    public static List<String> parseGcStatLine(String line) {
        String[] split = line.split(" ");
        List<String> lineValue = Arrays.stream(split)
                .filter(x -> StrUtil.isNotBlank(x))
                .collect(Collectors.toList());
        return lineValue;
    }

    public static <T> T toModel(Map<String, String> lineData, Class<T> clazz)
            throws Exception {
        T t = clazz.getConstructor().newInstance();

        for (Entry<String, String> e : lineData.entrySet()) {
            // 转小写
            String fieldName = e.getKey().toLowerCase();
            String value = e.getValue();
            // 获得字段
            Field field = clazz.getDeclaredField(fieldName);
            // 写入数据
            ReflectUtil.setFieldValue(t, field, value);
        }
        return t;
    }

    public static String getPid() {
        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        String name = runtimeMXBean.getName();
        long pid = Long.parseLong(name.split("@")[0]);
        return String.valueOf(pid);
    }

    public static double percent(double molecule, double denominator) {
        if (denominator == 0) {
            return 0;
        }
        double res = molecule / denominator * 100;
        return NumberUtil.round(res, 2).doubleValue();
    }

    public static double division(double molecule, double denominator) {
        if (denominator == 0) {
            return 0;
        }
        double res = molecule / denominator;
        return NumberUtil.round(res, 2).doubleValue();
    }


}
